import {createApp} from 'vue'
import {createPinia} from 'pinia'
import dynamicLoadWidget from '@/dynamic-widgets/index'
import {readConfig} from '@/api'
import processConfig from '@/logic/config'
import App from './App.vue'
import register2Global from '@/register.ts'
import registerGlobalComponents from '@/components/index'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import 'virtual:svg-icons-register'

import '@/styles/global.less'
import '@/styles/animation.less'
import '@/styles/reset.css'
import 'animate.css'
import 'uno.css'   // UnoCss


const app = createApp(App)

// 全局状态管理
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
app.use(pinia)

// window上挂载pinia实例
register2Global()
registerGlobalComponents(app)

// 加载全局配置
try {
    const config = await readConfig()
    app.config.globalProperties.$config = processConfig(config)
    console.log('%c加载全局配置成功', app.config.globalProperties.$config.log.formatter.success)
} catch (error) {
    console.error('加载全局配置失败:', error)
}

// 加载远程组件
try {
    const promiseMap = await dynamicLoadWidget(app.config.globalProperties.$config)
    console.group('开始注册组件...')
    promiseMap.forEach((component, name) => {
        console.log(
            `%c注册组件: <${name}>`,
            app.config.globalProperties.$config.log.formatter.success
        )
        app.component(name, component)
    })
    console.groupEnd()
} catch (error) {
    console.error(`%c${error}`, app.config.globalProperties.$config.log.formatter.error)
}

export default app
app.mount('#app')

